<template>
    <ContentWrap>
        <div class="flex justify-between">
            <div class="">
                <ElButton type="primary" :icon="Plus" @click="onAdd">
                    {{ t('新增角色') }}
                </ElButton>
            </div>
            <div class="">
                <ElInput v-model="state.searchData.keywords" style="width: 266px;height: 32px;margin-right: 10px;"
                    placeholder="请输入角色名称" :prefix-icon="Search" />
                <ElButton type="primary" :icon="Search" @click="onSearch">
                    {{ t('common.query') }}
                </ElButton>
                <ElButton :icon="Refresh" @click="onReset">
                    {{ t('common.reset') }}
                </ElButton>
            </div>
        </div>
        <div class="" style="margin-top: 25px;">
            <Table v-model:pageSize="pageSize" v-model:currentPage="currentPage" :columns="allSchemas.tableColumns"
                :data="dataList" :loading="loading" :pagination="{ total: total }" @register="tableRegister"
                :headerCellStyle="headerCellStyle" :rowStyle="rowStyle" />
        </div>
    </ContentWrap>
    <Dialog v-model="dialogVisible1" :title="state.dialogVisible1title" width="500">
        <el-form ref="ruleFormRef" :model="state.ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
            status-icon>
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="state.ruleForm.roleName" clearable placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item label="权限字符" prop="roleKey">
                <el-input v-model="state.ruleForm.roleKey" :disabled="state.ruleForm.roleKey == 'superadmin'" clearable
                    placeholder="请输入权限字符" />
            </el-form-item>
            <el-form-item label="角色顺序" prop="roleSort">
                <el-input-number v-model="state.ruleForm.roleSort" min="0" placeholder="请输入角色顺序" />
            </el-form-item>
            <el-form-item label="菜单权限" prop="menuIds" v-if="state.ruleForm.roleKey != 'superadmin'">
                <div class="">
                    <div class="">
                        <el-cascader v-model="state.ruleForm.menuIds" :options="state.options1" :props="props" collapse-tags
                            clearable placeholder="请输入菜单权限" style="width: 100%;" />
                    </div>
                    <!-- <el-checkbox-group v-model="state.ruleForm.type">
                        <el-checkbox label="展开/折叠" name="type" />
                        <el-checkbox label="全选/全不选" name="type" />
                        <el-checkbox label="父子联动" name="type" />
                    </el-checkbox-group> -->
                </div>
            </el-form-item>
            <el-form-item label="数据权限" prop="dataScope">
                <el-select v-model="state.ruleForm.dataScope" clearable collapse-tags class="m-2" placeholder="请选择数据权限">
                    <el-option v-for="item in state.options2" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="state.ruleForm.remark" placeholder="请输入备注" :autosize="{ minRows: 2}" type="textarea" row="4" />
            </el-form-item>
            <el-form-item>
                <div class="flex jcfe w-[100%]">
                    <el-button type="primary" v-loading="btn_loading" @click="submitForm(ruleFormRef)">保存</el-button>
                    <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                </div>
            </el-form-item>
        </el-form>
    </Dialog>
</template>
    
<script setup lang="tsx">
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { Dialog } from '@/components/Dialog'
import { useEmitt } from '@/hooks/event/useEmitt'
import { ElButton, ElInput, ElMessage, ElMessageBox } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { ContentWrap } from '@/components/ContentWrap'
import { ref, reactive, unref } from "vue"
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { getRoleListApi, addRoleApi, editRoleApi, deteleRoleApi, getRoleDetailApi } from "@/api/roles/index"
import { getMenuTreeSelectlistApi, getMenuTreeSelectDetailApi } from "@/api/menu/index"
import type { FormInstance, FormRules } from 'element-plus'
const btn_loading = ref(false)
const props = {
    checkStrictly: true,
    multiple: true,
    value: "id",
    label: "label",
    emitPath: false
}
interface RuleForm {
    roleName: string
    roleKey: string
    roleSort: string
    dataScope: string[]
    menuIds: string[]
}
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
    roleName: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min: 1, max: 50, message: '请输入1~50个字符', trigger: 'blur' },
    ],
    roleKey: [
        { required: true, message: '请输入权限字符', trigger: 'blur' },
        { min: 1, max: 50, message: '请输入1~50个字符', trigger: 'blur' },
    ],
    dataScope: [
        {
            required: true,
            message: '请选择数据权限',
            trigger: 'blur',
        },
    ],
    menuIds: [
        {
            type: 'array',
            required: true,
            message: '请选择菜单权限',
            trigger: 'change',
        },
    ]
})
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (state.dialogVisible1title == '新增角色') {
                let obj = {
                    "roleName": state.ruleForm.roleName,
                    "roleKey": state.ruleForm.roleKey,
                    "roleSort": state.ruleForm.roleSort,
                    "dataScope": state.ruleForm.dataScope,
                    "remark": state.ruleForm.remark,
                    "menuIds": state.ruleForm.menuIds,
                }
                console.log("新增角色：", obj);
                btn_loading.value = true
                addRoleApi(obj).then((res: any) => {
                    ElMessage({
                        type: 'success',
                        message: `${res.msg}`,
                    })
                    formEl.resetFields()
                    getList()
                    dialogVisible1.value = false
                    btn_loading.value = false
                }).catch((res: any) => {
                    ElMessage({
                        type: 'error',
                        message: `${res.msg}`,
                    })
                    btn_loading.value = false
                })
            } else {
                btn_loading.value = true
                editRoleApi(state.ruleForm).then((res: any) => {
                    ElMessage({
                        type: 'success',
                        message: `${res.msg}`,
                    })
                    formEl.resetFields()
                    getList()
                    dialogVisible1.value = false
                    btn_loading.value = false
                }).catch((res: any) => {
                    ElMessage({
                        type: 'error',
                        message: `${res.msg}`,
                    })
                    btn_loading.value = false
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
const resetForm = (formEl: FormInstance | undefined) => {
    dialogVisible1.value = false
    if (!formEl) return
    formEl.resetFields()
}
const { t } = useI18n()
const dialogVisible1 = ref(false)//定义职位详情弹框
const state = reactive({
    searchData: {
        companyValue: "",
        jobValue: "",
        keywords: ""
    },//搜索参数
    options1: [] as any,//所属下拉框
    options2: [
        { label: "全部数据权限", value: "1" },
        { label: "自定数据权限", value: "2" },
        { label: "本部门数据权限", value: "3"},
        { label: "本部门及以下数据权限", value: "4" }
    ] as any,//职位状态下拉框
    react: true,//分页刷新
    dialogVisible1title: "新增角色",
    ruleForm: {} as any,
})

// 表格基本信息
const crudSchemas = reactive<CrudSchema[]>([
    {
        field: 'roleName',
        label: t('角色名称'),
        search: {
            component: 'Input'
        },
        form: {
            component: 'Input',
            colProps: {
                span: 24
            }
        },
        detail: {
            span: 24
        }
    },
    {
        field: 'roleKey',
        label: t('权限字符'),
        search: {
            hidden: true
        }
    },
    {
        field: 'dataScope',
        label: t('数据权限'),
        search: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <div>{data[0].row.dataScope == 1 ? '全部数据权限' : data[0].row.dataScope == 2 ? "自定数据权限" : data[0].row.dataScope == 3 ? "本部门数据权限" : "本部门及以下数据权限"}</div>
                        </>
                    )
                }
            }
        }
    },
    {
        field: 'action',
        width: '260px',
        label: t('tableDemo.action'),
        search: {
            hidden: true
        },
        form: {
            hidden: true
        },
        detail: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <ElButton link type="primary" onClick={() => action(data[0].row)}>
                                {t('编辑')}
                            </ElButton>
                            {/* <ElButton link type="primary" onClick={() => receat(data[0].row)}>
                                {t('查看')}
                            </ElButton> */}
                            <ElButton link type="danger" onClick={() => delData(data[0].row)}>
                                {t('删除')}
                            </ElButton>

                        </>
                    )
                }
            }
        }
    }
])
const { tableRegister, tableState, tableMethods } = useTable({
    fetchDataApi: async () => {
        const { currentPage, pageSize } = tableState
        const res: any = await getRoleListApi({
            pageNum: state.react ? 1 : unref(currentPage),
            pageSize: unref(pageSize),
            roleName: state.searchData.keywords
        })
        console.log(res);
        state.react = false
        return {
            list: res.rows,
            total: res.total
        }
    }
})
// 表格头部信息
const headerCellStyle: any = {
    "background": "#F2F6FC",
    "height": "48px"
}
// 
const rowStyle: any = {
    "height": "48px"
}
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods
getList()
useEmitt({
    name: 'getList',
    callback: (type: string) => {
        if (type === 'add') {
            currentPage.value = 1
        }
        getList()
    }
})
const { allSchemas } = useCrudSchemas(crudSchemas)
// 新增
const onAdd = () => {
    console.log("新增角色");
    state.ruleForm = {}
    state.ruleForm.roleSort = 0
    state.ruleForm.dataScope = []
    state.ruleForm.menuIds = []
    dialogVisible1.value = true
    state.dialogVisible1title = t('新增角色')
}
const action = (row: any) => {
    state.ruleForm = row
    getMenuTreeSelectDetailApi_(row.roleId)
    state.dialogVisible1title = t('编辑角色')
}
const delData = (row: any) => {
    ElMessageBox.confirm('确认删除该角色？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern:,
        draggable: true,
        type: 'warning',
    })
        .then(() => {
            deteleRoleApi(row.roleId).then((res: any) => {
                getList()
                ElMessage({
                    type: 'success',
                    message: `${res.msg}`,
                })
            }).catch((res: any) => {
                ElMessage({
                    type: 'error',
                    message: `${res.msg}`,
                })
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}

// 查询
const onSearch = () => {
    console.log("查询");
    state.react = true
    getList()
}
// 重置
const onReset = () => {
    console.log("重置");
    state.searchData.companyValue = ""
    state.searchData.keywords = ""
    state.searchData.jobValue = ""
    state.react = true
    getList()
}

const getMenuTreeSelectlistApi_ = () => {
    getMenuTreeSelectlistApi({}).then((res: any) => {
        console.log("下拉框：",res);
        state.options1 = res.data
    })
}
const getMenuTreeSelectDetailApi_ = (params) => {
    getMenuTreeSelectDetailApi(params).then((res: any) => {
        console.log(res);
        dialogVisible1.value = true
        let array = [] as any
        res.data.checkedKeys.forEach(element => {
            array.push(element)
        });
        state.ruleForm.menuIds = array
    })
}
getMenuTreeSelectlistApi_()
</script>
    
<style lang="less" scoped></style>